package com.ken.app.config;

import com.ken.app.entity.User;
import com.ken.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.Collection;
import java.util.HashSet;


/**
 *
 * Author: Liuk
 * Mail: leo_work@aliyun.com
 * Date: 2017/8/15 0015
 * Desc: 用户信息认证
 *
 */
@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Inject
    private UserService userService;

    /**
     * 根据用户名获取登录用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if(user == null){
             throw new UsernameNotFoundException("用户名："+ username + "不存在！");
        }
        log.info("获取加载的用户信息{}",user.toString());
        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
//        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("hasRole('admin')");
//        collection.add(simpleGrantedAuthority);
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),collection);
    }
}
